<template>
  <!-- fqc及oqc, ipqc检验报表界面 -->
  <div>
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :search.sync="query"
        :data="data"
        :page.sync="page"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <div style="display: flex">
            <!-- <el-button type="primary" size="small">查看报告</el-button> -->
          </div>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text" icon="el-icon-view" size="small" v-if="permission.ipqcCheckSheet_view" @click.stop="handleView(scope.row)">查看 </el-button>
        </template>
        <!-- <template slot="menu" slot-scope="{ row }">
            <el-button type="text" @click="viewReport(row.id)" size="small">查看报告</el-button>
          </template> -->
      </avue-crud>
      <el-dialog ref="dialog" title="查看" append-to-body :visible.sync="showDialog" v-if="showDialog" :close-on-click-modal="dialogClose">
        <el-tabs type="card" v-if="showDialog" v-model="tabsIndex">
          <el-tab-pane label="检验项详情" name="1">
            <avue-form ref="aplProperties" v-model="viewModel" :option="viewOption">
              <template slot="info" v-if="viewModel.attributeResultVOList && viewModel.attributeResultVOList.length > 0">
                <avue-form
                  ref="itemProperties"
                  v-for="(item, index) in viewModel.attributeResultVOList || []"
                  v-model="viewModel.attributeResultVOList[index]"
                  :option="itemOption"
                  :key="index"
                >
                  <template slot="info2">
                    <span style="display: block">检验项： {{ item.item ? item.item.itemName : '' }}</span>
                    <span style="display: block">检验明细项：{{ item.itemAttributeName }}</span>
                    <span style="display: block">检验标准：{{ item.testCriterion }}</span>
                    <span style="display: block">检验工具：{{ item.testTool }}</span>
                    <div v-if="item.examineRealValue.type === 'SELECT'">
                      <div style="display: flex; flex-direction: row" v-for="(selectItem, index2) in item.examineRealValue.options" :key="index2">
                        <label>{{ selectItem.label }}：</label>
                        <div style="width: 200px; margin-top: 5px">
                          <el-select disabled v-model="selectItem.selectValue">
                            <el-option v-for="item3 in selectItem.selectList" :key="item3.dictKey" :label="item3.dictValue" :value="item3.dictKey"> </el-option>
                          </el-select>
                        </div>
                      </div>
                    </div>
                    <div v-if="item.examineRealValue.type === 'SINGLE-INPUT'">
                      <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                        <label>{{ scanItem.label }}：</label>
                        <el-input style="width: 200px; margin-bottom: 5px" :value="scanItem.value" :disabled="true"> </el-input>
                      </div>
                    </div>
                    <div v-if="item.examineRealValue.type === 'MULTIPLE-INPUT'">
                      <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2" style="margin-bottom: 5px">
                        <label>{{ scanItem.label }}：</label>
                        <table border="1">
                          <tr>
                            <th width="50" style="text-align: center">次数</th>
                            <th width="70" style="text-align: center">测试值</th>
                            <th width="120" style="text-align: center">测试结果</th>
                            <th width="70" style="text-align: center">操作</th>
                          </tr>
                          <tr v-for="(result, index3) in item.examineRealValue.options[index2].valueResults" :key="index3">
                            <td style="text-align: center">{{ result.sequence }}</td>
                            <td style="text-align: center">{{ result.value }}</td>
                            <td style="text-align: center">
                              <span>{{ result.result }}</span>
                              <!-- <span style="margin-right: 2px"><input checked type="radio"/>OK</span> <span><input type="radio"/>NG</span> -->
                            </td>
                            <td style="text-align: center; color: red"><div>x</div></td>
                          </tr>
                        </table>
                      </div>
                    </div>
                    <div v-if="item.examineRealValue.type === 'RADIO'">
                      <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                        <label>{{ scanItem.label }}：</label>
                        <el-radio v-model="scanItem.valueResults" disabled :label="scanItem.realLabel">{{ scanItem.realLabel }}</el-radio>
                        <el-radio v-model="scanItem.valueResults" disabled :label="scanItem.shamLabel">{{ scanItem.shamLabel }}</el-radio>
                      </div>
                    </div>
                    <div v-if="item.examineRealValue.type === 'SCAN'">
                      <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                        <label>{{ scanItem.label + '数量' }}：</label>
                        <el-input style="width: 200px" :value="item.examineRealValue.scanContent.length" :disabled="true"> </el-input>
                      </div>
                    </div>
                    <div>
                      <label>不良登记：</label>
                      <table border="1">
                        <tr>
                          <th width="120" style="text-align: center">严重程度</th>
                          <th width="70" style="text-align: center">不良数量</th>
                          <th width="70" style="text-align: center">条码类型</th>
                          <th width="400" style="text-align: center">不良条码</th>
                        </tr>
                        <tr>
                          <td style="text-align: center">严重问题（CRI）</td>
                          <td style="text-align: center">{{ viewModel.attributeResultVOList[index].criQuantity || '' }}</td>
                          <td style="text-align: center">
                            {{ viewModel.attributeResultVOList[index].criList.length > 0 && viewModel.attributeResultVOList[index].criList[0].objectType | packTypefilter }}
                          </td>
                          <td style="text-align: center">{{ viewModel.attributeResultVOList[index].criList | defectfilter }}</td>
                        </tr>
                        <tr>
                          <td style="text-align: center">主要问题（MAJ）</td>
                          <td style="text-align: center">{{ viewModel.attributeResultVOList[index].majQuantity || '' }}</td>
                          <td style="text-align: center">
                            {{ viewModel.attributeResultVOList[index].majList.length > 0 && viewModel.attributeResultVOList[index].majList[0].objectType | packTypefilter }}
                          </td>
                          <td style="text-align: center">{{ viewModel.attributeResultVOList[index].majList | defectfilter }}</td>
                        </tr>
                        <tr>
                          <td style="text-align: center">次要问题（MIN）</td>
                          <td style="text-align: center">{{ viewModel.attributeResultVOList[index].minQuantity || '' }}</td>
                          <td style="text-align: center">
                            {{ viewModel.attributeResultVOList[index].minList.length > 0 && viewModel.attributeResultVOList[index].minList[0].objectType | packTypefilter }}
                          </td>
                          <td style="text-align: center">{{ viewModel.attributeResultVOList[index].minList | defectfilter }}</td>
                        </tr>
                      </table>
                    </div>
                  </template>
                </avue-form>
              </template>
              <template slot="info" v-else>
                <span></span>
              </template>
              <!-- <template slot="attachments">
                <div>
                  <div style="display: inline-block; text-align: center" v-for="(item, index) in viewModel.attachments" :key="item.attachmentId">
                    <img style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="item.link" @click="openPreview(index, item.link)" />
                  </div>
                </div>
              </template> -->
              <template slot="attachments">
                <!-------------------->
                <div>
                  <div style="display: inline-block; text-align: center" v-for="(item, index) in viewModel.attachments" :key="item.attachmentId">
                    <el-image
                      v-if="item.attachmentType === 'PICTURE'"
                      style="width: 100px; height: 100px; padding-right: 10px; display: block"
                      :src="item.link"
                      @click="openPreview(index, item.link)"
                    ></el-image>
                    <i
                      v-else
                      style="font-size: 70px; color: #909399; width: 100px; height: 100px; padding-right: 10px; display: block"
                      class="el-icon-document"
                      @click="openPreview(index, item.link)"
                    ></i>
                    <el-button type="text" v-if="item.link" icon="el-icon-download" size="small" @click="handleDownload(item)">下载 </el-button>
                  </div>
                </div>
              </template>
            </avue-form>
          </el-tab-pane>
          <el-tab-pane label="条码记录" name="2">
            <avue-form v-model="detailData" :option="detailOption"></avue-form>
          </el-tab-pane>
          <!-- <el-tab-pane label="AQL" name="3">
            <div v-for="(item, index) in inspectionAqlList" :key="index">
              <avue-form v-model="inspectionAqlList[index]" :option="aqlOption"> </avue-form>
            </div>
          </el-tab-pane> -->
        </el-tabs>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { getPage, getDetail } from '@/api/quality/checkLists.js';
import { mapGetters } from 'vuex';

export default {
  filters: {
    packTypefilter(type) {
      switch (type) {
        case 'PACKING':
          return '包装条码';
        case 'PRODUCT':
          return '产品';
        case 'CARRIER':
          return '载具';
        default:
          break;
      }
    },
    defectfilter(data) {
      let arr = data || [];
      let objectSns = arr.map((item) => {
        return item.objectSn;
      });
      return String(objectSns);
    }
  },
  data() {
    return {
      form: {
        deptId: '',
        lineId: ''
      },
      search: {},
      query: {},
      viewModel: {},
      loading: true,
      showDialog: false,
      tabsIndex: '1',
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      detailData: [],
      // 判断是在那个routeName下的
      selectRouteObj: {
        docType: ''
      },
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 18,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        dialogClickModal: false,
        searchLabelWidth: 120,
        labelWidth: 120,
        // searchSpan: 6,
        addBtn: false,
        // 操作栏不展示
        menu: true,
        menuWidth: 100,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        // 查看
        viewBtn: false,
        column: [
          {
            label: '类型',
            prop: 'documentType',
            type: 'select',
            search: true,
            value: 'IPQC',
            // dicUrl: '/api/blade-system/dict/dictionary?code=document_sub_type',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // },
            dicData: [
              // {
              //   label: '全部',
              //   value: 'IPQC,FAI,LAI'
              // },
              {
                label: '巡检',
                value: 'IPQC'
              },
              {
                label: '首检',
                value: 'FAI'
              },
              {
                label: '末检',
                value: 'LAI'
              }
            ]
          },
          {
            label: '检验单号',
            prop: 'documentNo',
            search: true,
            minWidth: 150
          },
          {
            label: '检验状态',
            prop: 'status',
            type: 'select',
            value: '2',
            search: true,
            dicData: [
              {
                label: '未检验',
                value: 1
              },
              {
                label: '已检验',
                value: 2
              }
            ]
          },
          {
            label: '工单号',
            minWidth: 150,
            search: true,
            prop: 'sourceNo'
          },
          {
            label: '产线',
            prop: 'lineName'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            minWidth: 100
          },
          {
            label: '产品名称',
            minWidth: 100,
            prop: 'partName'
          },
          {
            label: '报检日期',
            minWidth: 150,
            prop: 'sendExamineDate',
            type: 'datetime'
          },
          {
            label: '检验日期',
            minWidth: 150,
            prop: 'examineDate',
            type: 'datetime',
            search: true,
            searchType: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '检验人员',
            prop: 'examineByName'
          }
        ]
      },
      viewOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: '160',
        column: [
          {
            labelWidth: 60,
            label: '',
            prop: 'info',
            span: 24,
            hide: true,
            row: true,
            formslot: true
          },
          {
            label: '综合判定结果',
            prop: 'examineResult',
            type: 'radio',
            span: 24,
            disabled: true,
            labelWidth: 100,
            row: true,
            dicData: [
              {
                label: 'OK',
                value: 'OK'
              },
              {
                label: 'NG',
                value: 'NG'
              }
            ]
          },
          {
            label: '附件',
            prop: 'attachments',
            span: 24,
            formslot: true,
            disabled: true
          },
          {
            label: '备注/原因',
            prop: 'remark',
            span: 20,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            disabled: true,
            row: true
          }
        ]
      },
      itemOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: '160',
        column: [
          {
            labelWidth: 60,
            label: '',
            prop: 'info2',
            span: 24,
            hide: true
          },
          {
            label: '检验结果',
            prop: 'examineResult',
            type: 'radio',
            span: 24,
            disabled: true,
            labelWidth: 100,
            row: true,
            formslot: true,
            dicData: [
              {
                label: 'OK',
                value: 'OK'
              },
              {
                label: 'NG',
                value: 'NG'
              }
            ]
          }
        ]
      },
      detailOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '检验条码',
            prop: 'objectSn',
            type: 'textarea',
            rows: 5,
            span: 24,
            disabled: true,
            placeholder: '检验条码'
          },
          {
            label: '不良条码',
            prop: 'NGSn',
            type: 'textarea',
            rows: 5,
            span: 24,
            disabled: true,
            placeholder: '不良条码'
          }
        ]
      },
      data: [],
      dialogVisible: false,
      dialogForm: {
        isQualified: null
      },
      // 车间列表
      workshopList: [],
      repairSuccessVisible: false,
      repairSuccessForm: {
        scrapReason: ''
      },
      rulesSuccessForm: {
        scrapReason: [{ required: true, message: '请输入报废原因', trigger: 'blur' }]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 通过 `vm` 访问组件实例

      vm.page = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
      vm.query = {};

      vm.init();

      vm.searchReset();
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    viewReport(id) {
      // if (this.selectRouteObj.documentType === 'IPQC') {
      //   window.open(`${this.website.reportUrl}/preview?_u=blade-11.ureport.xml&qcId=${id}`);
      // } else {
      //   window.open(`${this.website.reportUrl}/preview?_u=blade-OQC.ureport.xml&qcId=${id}`);
      // }
      // this.$router.push({ path: `/myiframe/urlPath?name=preview-11&src=http://192.168.1.199:8108/ureport/preview?_u=blade-11.ureport.xml&ipqcId=${id}` });
    },
    init() {
      // const columnItem = this.findObject(this.option.column, 'partnerName');
      // const sendExamineQuantity = this.findObject(this.option.column, 'sendExamineQuantity');
      // switch (this.$route.path) {
      //   case '/quality/checkReports/1':
      //     this.option.column[1].label = '工单号';
      //     this.selectRouteObj.documentType = 'FQC';
      //     columnItem.hide = true;
      //     sendExamineQuantity.hide = false;
      //     break;
      //   case '/quality/checkReports/2':
      //     this.option.column[1].label = '发货单号';
      //     this.selectRouteObj.documentType = 'OQC';
      //     columnItem.hide = false;
      //     sendExamineQuantity.hide = false;
      //     break;
      //   case '/quality/checkReports/3':
      //     this.option.column[1].label = '工单号';
      //     this.selectRouteObj.documentType = 'IPQC';
      //     columnItem.hide = true;
      //     sendExamineQuantity.hide = true;
      //     break;
      // }
      // this.refreshChange()
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      // console.log(params, this.query, 88877788)
      if (params.examineDate && params.examineDate.length > 0) {
        params.startExamineDate = params.examineDate[0];
        params.endExamineDate = params.examineDate[1];
        delete params.examineDate;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      // this.init();
      this.loading = true;
      if (!params.documentType) {
        params.docType = 'IPQC,FAI,LAI';
      } else {
        params.docType = params.documentType;
      }
      delete params.documentType;
      // params.status = this.selectRouteObj.status;
      params.descs = 'send_examine_date';
      getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleDownload(item) {
      window.open(`${item.link}`);
    },
    handleView(row) {
      this.tabsIndex = '1';
      getDetail(row.id).then((res) => {
        let data = res.data.data;
        this.viewModel = data;
        //检验项数据
        this._forEach(this.viewModel.attributeResultVOList || [], (item) => {
          if (!item.criList) {
            item.criList = [];
          }
          if (!item.majList) {
            item.majList = [];
          }
          if (!item.minList) {
            item.minList = [];
          }
          item.examineRealValue = JSON.parse(item.examineRealValue);
        });
        //条码记录
        let objectSn = [];
        let NGSn = [];
        this._forEach(data.inspectionObjectList, (item) => {
          objectSn.push(item.objectSn);
          if (item.isNg) {
            NGSn.push(item.objectSn);
          }
        });
        // this.detailData.objectSn = objectSn.join('、');
        this.detailData.NGSn = NGSn.join('、');
      });

      this.showDialog = true;
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    }
  }
};
</script>

<style></style>
